<!--
 * @Author: 李天惊 uf_lee@163.com
 * @Date: 2022-08-15 16:45:26
 * @LastEditors: 李天惊 uf_lee@163.com
 * @LastEditTime: 2023-01-02 20:44:14
 * @FilePath: \grazlink20\uc_sys\src\views\Asset\Pasture\components\Assets.vue
 * Copyright (c) 2022 by 李天惊 uf_lee@163.com, All Rights Reserved. 
 * 单个牧场-打标资产
-->
<script setup lang="ts">
import { reactive, PropType, watch, ref, unref } from 'vue'
import { ElButton } from 'element-plus'
import { Search } from '@/components/Search'
// import { LeeSearch } from '@/components/Lee/Search'
import { Table } from '@/components/Table'
import { Dialog } from '@/components/Dialog'

import See from '@/views/Asset/Assets/components/See.vue'

import { zcMarkOrderDetailedListApi } from '@/api/cy/xMarking'
import { sysDictRelsApi } from '@/api/dict'
import { CrudSchema, useCrudSchemas } from '@/hooks/web/useCrudSchemas'
import { useTable } from '@/hooks/web/useTableTest'
import { useIcon } from '@/hooks/web/useIcon'
// 获取字典
import { useCache } from '@/hooks/web/useCache'
const { wsCache } = useCache()
const dict: any = wsCache.get('dict')
// 字典通过value获取label
const getDictLabel = (type, value) => {
  let data = dict[type].find((item) => {
    return item.value == value
  })
  return data ? data.label : ''
}

const iconSee = useIcon({ icon: 'ep:view' })

const dictRelsData = ref() // 联动数据

const breedSubData = ref([]) // 品种的枚举

const searchRef = ref() // 搜索的标签

const dialogVisible = ref(false)
const dialogTitle = ref('')
const actionType = ref('')

// 获取联动关系
const getDictRels = async () => {
  const res = await sysDictRelsApi({
    p_type: 'breed',
    c_type: 'breed_sub'
  })
    .catch(() => {})
    .finally(() => {})
  if (res) {
    dictRelsData.value = res.data
  }
}

// 根据畜别查询品种
const breedGetSub = async (breed_value) => {
  // console.log('breed_value', breed_value, !breed_value)
  if (!breed_value) {
    breedSubData.value = []
  } else {
    let breedData = dictRelsData.value.find((item) => {
      return item.value == breed_value
    })
    breedSubData.value = breedData.children
  }
}

const props = defineProps({
  currentRow: {
    type: Object as PropType<Nullable<any>>,
    default: () => null
  }
})

const { register, tableObject, methods } = useTable<
  {
    total: number
    list: any[]
  },
  any
>({
  getListApi: zcMarkOrderDetailedListApi,
  response: {
    data: 'data',
    count: 'count'
  }
})
const { getList, setSearchParams } = methods

// 选择畜别的时候触发，处理品种类容
const breedChange = (value) => {
  breedGetSub(value)
  const new_search = unref(searchRef)
  new_search.setData({ ...new_search.getData(), breed_sub: '' })
}

const crudSchemas = reactive<CrudSchema[]>([
  {
    field: 'id',
    label: '主键',
    fixed: 'left',
    width: 100,
    table: {
      show: true
    },
    form: {
      show: false
    },
    detail: {
      show: false
    }
  },
  // {
  //   field: 'customer_code',
  //   label: '牧场编码',
  //   width: 150,
  //   search: {
  //     show: true
  //   }
  // },
  // {
  //   field: 'customer_name',
  //   label: '牧场名称',
  //   width: 150,
  //   search: {
  //     show: true
  //   }
  // },
  {
    field: 'asset_code',
    label: '注射编码',
    width: 150,
    search: {
      show: true
    }
  },
  {
    field: 'asset_code_2',
    label: '项圈编码',
    width: 150,
    search: {
      show: true
    }
  },
  {
    field: 'earcon_code',
    label: '耳标号',
    width: 150,
    search: {
      show: true
    }
  },
  {
    field: 'breed',
    label: '畜别',
    width: 80,
    formatter: (_: Recordable, __: TableColumn, cellValue: number | string) => {
      return getDictLabel('breed', cellValue)
    },
    search: {
      component: 'Select',
      componentProps: {
        options: dict.breed,
        onChange: breedChange
      },
      show: false
    }
  },
  {
    field: 'breed_sub',
    label: '品种',
    width: 120,
    formatter: (_: Recordable, __: TableColumn, cellValue: number | string) => {
      return getDictLabel('breed_sub', cellValue)
    },
    search: {
      component: 'Select',
      componentProps: {
        options: breedSubData
      },
      show: false
    }
  },
  {
    field: 'sex',
    label: '性别',
    width: 150,
    formatter: (_: Recordable, __: TableColumn, cellValue: number | string) => {
      return getDictLabel('animal_sex', cellValue)
    },
    search: {
      component: 'Select',
      componentProps: {
        options: dict.animal_sex
      },
      show: false
    }
  },
  {
    field: 'month_age',
    label: '月龄',
    width: 150,
    search: {
      show: false
    }
  },
  {
    field: 'purpose',
    label: '用途',
    formatter: (_: Recordable, __: TableColumn, cellValue: number | string) => {
      return getDictLabel('purpose', cellValue)
    },
    width: 150,
    search: {
      component: 'Select',
      componentProps: {
        options: dict.purpose
      },
      show: false
    }
  },
  // {
  //   field: 'creation_time',
  //   label: '创建时间',
  //   width: 170,
  //   form: {
  //     show: true,
  //     component: 'DatePicker',
  //     componentProps: {
  //       disabled: true,
  //       type: 'datetime',
  //       valueFormat: 'YYYY-MM-DD HH:mm:ss'
  //     }
  //   },
  //   search: {
  //     show: true,
  //     component: 'DatePicker',
  //     componentProps: {
  //       'is-range': true,
  //       'unlink-panels': true,
  //       rangeSeparator: 'To',
  //       type: 'daterange',
  //       valueFormat: 'YYYY-MM-DD HH:mm:ss'
  //     }
  //   }
  // },
  // {
  //   field: 'update_user_name',
  //   label: '创建人',
  //   width: 80,
  //   form: {
  //     show: false
  //   }
  // },
  {
    field: 'action',
    width: 60,
    fixed: 'right',
    label: '操作',
    form: {
      show: false
    },
    detail: {
      show: false
    }
  }
])

const { allSchemas } = useCrudSchemas(crudSchemas)

const action = async (type: string, row: any = {}) => {
  actionType.value = type
  switch (type) {
    case 'see':
      dialogTitle.value = '健康档案'
      tableObject.currentRow = row
      dialogVisible.value = true
      break
    default:
      console.log('未知类型')
  }
}

/****************************** 监听设置固定条件 start ******************************/
const newFixedSearch = ref({})
watch(
  () => props.currentRow,
  (val: any) => {
    console.log(val, 'val')
    if (!val) return
    // 设置固定条件
    newFixedSearch.value = {
      mark_order_id: val.id
    }
    tableObject.fixedSearch = newFixedSearch.value
  },
  {
    deep: true,
    immediate: true
  }
)
/****************************** 监听设置固定条件 start ******************************/

/****************************** 初始化 start ******************************/
const init = async () => {
  // 列表查询
  await getList()
  // 获取关联关系
  await getDictRels()
  // console.log('dictRelsData', dictRelsData.value)
}
init()
/****************************** 初始化 end ******************************/
</script>

<template>
  <div>
    <!-- <LeeSearch :schema="allSchemas.searchSchema" /> -->
    <Search
      ref="searchRef"
      :schema="allSchemas.searchSchema"
      @search="setSearchParams"
      @reset="setSearchParams"
    />

    <Table
      v-model:pageSize="tableObject.pageSize"
      v-model:currentPage="tableObject.currentPage"
      :columns="allSchemas.tableColumns"
      :data="tableObject.tableList"
      :loading="tableObject.loading"
      :border="true"
      :pagination="{
        total: tableObject.count
      }"
      @register="register"
      :selection="false"
    >
      <template #action="{ row }">
        <ElButton circle :icon="iconSee" @click="action('see', row)" title="健康档案" />
      </template>
    </Table>

    <Dialog v-model="dialogVisible" :title="dialogTitle">
      <See
        v-if="actionType == 'see'"
        :detail-schema="allSchemas.detailSchema"
        :current-row="tableObject.currentRow"
      />
      <template #footer>
        <ElButton @click="dialogVisible = false">关闭</ElButton>
      </template>
    </Dialog>
  </div>
</template>
